package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.pojo.Category;
import com.itheima.reggie.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @title: CategoryController
 * @Author 椎名真白
 * @Date: 2022-04-28 11:00
 * @Version 1.0
 */
@Slf4j
@RestController
@RequestMapping("category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    /**
     * @description: 添加分类信息
     * @author: 椎名真白
     * @date: 2022-04-28 11:04
     * @param: category
     * @return: com.itheima.reggie.common.R<java.lang.String>
     **/
    @PostMapping
    public R<String> add(@RequestBody Category category) {
        categoryService.save(category);
        return R.success("添加成功");
    }

    /**
     * @description: 分页查询
     * @author: 椎名真白
     * @date: 2022-04-28 15:59
     * @param: page
     * @param: pageSize
     * @return: com.itheima.reggie.common.R<com.baomidou.mybatisplus.extension.plugins.pagination.Page>
     **/
    @GetMapping("page")
    public R<Page> page(Integer page, Integer pageSize) {
        //构造分页器
        Page pageInfo = new Page(page, pageSize);
        //构造条件选择器
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("update_time").orderByAsc("sort");
        categoryService.page(pageInfo, queryWrapper);
        return R.success(pageInfo);
    }

    @DeleteMapping
    public R<String> delete(Long ids) {
        log.info("要删除的分类id为:{}", ids);
        //不在调用自带的删除方法，使用增强后的删除
        //categoryService.removeById(ids);
        categoryService.remove(ids);
        return R.success("删除成功");
    }

    @PutMapping
    public R<String> update(@RequestBody Category category) {
        categoryService.updateById(category);
        return R.success("修改成功");
    }


    @GetMapping("list")
    public R<List<Category>> list(Integer type) {
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(type != null, "type", type);
        List<Category> list = categoryService.list(queryWrapper);
        return R.success(list);
    }
}
